
--runTag 0-local 1-shopwegame 2-online
local runTag = 0
-- *5s  *2s
local maxAttemptsUser, maxAttemptsAccept = 12 * 5, 30 * 5
local baseUrl, authSecret = "https://u7playearn.shopwegame.com/dev-api/play-earn/api/order", "8f9dbe334ca364eac2b18ca437fde25d"
if runTag == 0 then
    maxAttemptsUser, maxAttemptsAccept = 12 * 1, 30 * 2
elseif runTag == 1 then
    maxAttemptsUser, maxAttemptsAccept = 12 * 3, 30 * 4
else
    baseUrl = "https://u7playearn.shopwegame.com/dev-api/play-earn/api/order"
    authSecret = "8f9dbe334ca364eac2b18ca437fde25d"
end
local LocalPlayerName = game.Players.LocalPlayer.Name
local HttpService = game:GetService("HttpService")
local Trade = game:GetService("ReplicatedStorage").Trade
local GetFullInventory = game:GetService("ReplicatedStorage").Remotes.Extras.GetFullInventory
local Players = game:GetService("Players")
local game_id = game.PlaceId * 2
math.randomseed(os.time())
local log = function(s)
    local success, err = pcall(function()
        appendfile("log.txt", string.format("[%s] %s\n", os.date("%Y-%m-%d %H:%M:%S"), tostring(s)))
    end)
    if not success then
        writefile("log.txt", string.format("[%s] %s\n", os.date("%Y-%m-%d %H:%M:%S"), tostring(s)))
    end
end
function httpGet(url)
    local success, result = pcall(function()
        return game:HttpGet(url, true)
    end)
    return success and result or (log("url请求失败：" .. url))
end

local function jump()
    --log("jump")
    local keys = { 0x20, 0x20, 0x20, 0x20, 0x41, 0x44, 0x53, 0x57 }
    local randomKey = keys[math.random(1, #keys)]
    pcall(function()
        keypress(randomKey)
        task.wait(0.2)
        keyrelease(randomKey)
    end)
end

task.spawn(function()
    while task.wait(60) do
        jump()
    end
end)
local function getReceivingOrder()
    if runTag == 0 then
        return {
            user = "pssmurf0077",
            itemId = "Saw",
            trade_num = 1,
            orderProductId = "20251",
            order_id = "2025"
        }
    end
    local url = string.format("%s/query?authSecret=%s&robloxUserName=%s", baseUrl, authSecret, LocalPlayerName)
    local success, response = pcall(function()
        local result = httpGet(url)
        local result_d = HttpService:JSONDecode(result)
        if result_d.code == 200 then
            local data = result_d.data
            log("获取收货orderId: " .. tostring(data.orderId))
            return {
                user = data.robloxUserName,
                itemId = data.product.tradeId,
                orderProductId = data.product.orderProductId,
                trade_num = data.product.quantity,
                order_id = data.orderId
            }
        else return {}
        end
    end)
    if not success then
        log("getReceivingOrder 请求失败: " .. tostring(response))
    end
    if type(response) == "table" then
        return response
    else return {}
    end
end

local function getDeliveryOrder()
    local url = "http://fifa-player.shopwegame.com/api/fifa/sbc/list"
    local success, response = pcall(function()
        local result = httpGet(url)
        log("请求URL: " .. url)
        log("响应长度: " .. tostring(#result) .. " 字符")
        local result_d = HttpService:JSONDecode(result)
        -- log("sbc_task_id: " .. result_d.data[1]["sbc_task_id"])
        log(result)
        local preview = string.sub(result, 1, 100)
        log("响应预览:\n" .. preview .. "...")
        return result
    end)
    if not success then
        log("请求失败: " .. tostring(response))
    end
end

local function sendTradeRequest(user)
    local p = Players:FindFirstChild(user)
    if p then
        local args = { [1] = p }
        Trade.SendRequest:InvokeServer(unpack(args))
        return true
    end
end

local function getCurTradeStatus()
    local status, tradeData = Trade.GetTradeStatus:InvokeServer()
    if status ~= "SendingRequest" then
        log("交易状态" .. status)
    end
    return status, tradeData
end
local function checkUser(user)
    local num = 0
    while num < maxAttemptsUser do
        local p = Players:FindFirstChild(user)
        if p then
            return true
        end
        wait(5)
        num = num + 1
    end
    return false
end

local function checkItem(itemId)
    local InventoryData = GetFullInventory:InvokeServer(LocalPlayerName)["Weapons"]["Owned"]
    if typeof(InventoryData) == "table" then
        local json = HttpService:JSONEncode(InventoryData)
        log("库存:" .. json)
    end
    if InventoryData[itemId] then
        return true
    else
        return false
    end
end

local function getItemNum(itemId)
    local InventoryData = GetFullInventory:InvokeServer(LocalPlayerName)["Weapons"]["Owned"]
    local json = HttpService:JSONEncode(InventoryData)
    log("库存:" .. json)
    return InventoryData[itemId] or 0
end

local function reportOrder(data)
    local orderStatus, receiveStatus, orderId = data["orderStatus"], data["receiveStatus"], data["order_id"]
    --orderStatus 2 订单开始 4订单结束
    --receiveStatus 1 成功 2 卖家未进私服 3 交易超时(包括物品不对，未确认等) 4 其它错误
    local url = ""
    if orderStatus == 2 then
        url = string.format(
                "%s/sync?authSecret=%s&orderId=%s&orderStatus=2",
                baseUrl, authSecret, orderId
        )
    elseif orderStatus == 4 then
        if receiveStatus == 1 then
            url = string.format(
                    "%s/sync?authSecret=%s&orderId=%s&orderStatus=4&receiveStatus=1&orderProductId=%s&quantity=%s",
                    baseUrl, authSecret, orderId, data["orderProductId"], data["addNum"]
            )
        else
            url = string.format(
                    "%s/sync?authSecret=%s&orderId=%s&orderStatus=4&receiveStatus=%s",
                    baseUrl, authSecret, orderId, receiveStatus
            )
        end
    end
    log("回调url: " .. url)
    if runTag ~= 0 then
        local reportRes = httpGet(url)
        log("回调res: " .. reportRes)
    end
end
local function runReceiving(data)
    local success, response = pcall(function()
        local user, orderId = data["user"], data["order_id"]
        local itemId, orderProductId, trade_num = data["itemId"], data["orderProductId"], data["trade_num"]
        local curItemIdCount = getItemNum(itemId)
        log(string.format("收货orderId:%s user:%s item:%s 有%s个 开始交易", orderId, user, itemId, curItemIdCount))
        data["orderStatus"] = 2
        reportOrder(data)
        local hasUser = checkUser(user)
        if not hasUser then
            log(string.format("收货orderId:%s user:%s 未进私服", orderId, user))
            data["orderStatus"], data["receiveStatus"] = 4, 2
            reportOrder(data)
            return
        end
        local curTradeStatus, tradeData = getCurTradeStatus()
        if curTradeStatus == "StartTrade" then
            Trade.DeclineTrade:FireServer()
            wait(0.5)
        end
        wait(2)
        local getItemId, num = false, 0
        while not getItemId do
            local curTradeStatus, tradeData = getCurTradeStatus()
            if curTradeStatus == "StartTrade" and tradeData["Player2"]["Accepted"] then
                for i, item in ipairs(tradeData.Player2.Offer) do
                    if item[1] == itemId then
                        log(string.format("收货 orderId:%s user:%s item:%s 命中", orderId, user, itemId))
                        local acceptArgs = { [1] = game_id }
                        Trade.AcceptTrade:FireServer(unpack(acceptArgs))
                        wait(1)
                        local acceptItemIdCount = getItemNum(itemId)
                        local addNum = acceptItemIdCount - curItemIdCount
                        if addNum > 0 then
                            log(string.format(
                                    "收货 orderId:%s user:%s item:%s trade_num：%s 新增:%s个",
                                    orderId, user, itemId, trade_num, addNum))
                            getItemId = true
                            data["orderStatus"], data["receiveStatus"], data["addNum"] = 4, 1, addNum
                            reportOrder(data)
                        end
                    end
                end
            elseif curTradeStatus == "None" then
                local sendRes = sendTradeRequest(user)
                if not sendRes then
                    log(string.format("收货orderId:%s user:%s 中途退出", orderId, user))
                    data["orderStatus"], data["receiveStatus"] = 4, 4
                    reportOrder(data)
                    break
                else
                    log(string.format("收货orderId:%s user:%s sendTradeRequest", orderId, user))
                end
            elseif curTradeStatus == "ReceivingRequest" then
                Trade.DeclineRequest:FireServer()
                wait(0.5)
            end
            wait(2)
            num = num + 1
            if num > maxAttemptsAccept then
                log(string.format("收货 orderId:%s user:%s item:%s 交易超时", orderId, user, itemId))
                data["orderStatus"], data["receiveStatus"] = 4, 3
                reportOrder(data)
                break
            end
        end

    end)
    if not success then
        log("runReceiving err: " .. tostring(response))
        data["orderStatus"], data["receiveStatus"] = 4, 4
        reportOrder(data)
    end
end
local function runDelivery(data)
    local user, itemId, orderId = data["user"], data["itemId"], data["order_id"]
    log(string.format("发货orderId:%s user:%s item:%s 开始交易", orderId, user, itemId))
    local hasUser = checkUser(user)
    if not hasUser then
        log(string.format("发货orderId:%s user:%s 未进私服", orderId, user))
    end
    local hasItem = checkItem(itemId)
    if not hasItem then
        log(string.format("发货orderId:%s user:%s item:%s 无此库存", orderId, user, itemId))
    end
    local curTradeStatus, tradeData = getCurTradeStatus()
    if curTradeStatus == "StartTrade" then
        Trade.DeclineTrade:FireServer()
        wait(0.5)
    end
    wait(2)

    local orderEnd = false
    while true do
        local curTradeStatus, tradeData = getCurTradeStatus()
        if curTradeStatus == "StartTrade" then
            break
        elseif curTradeStatus == "None" then
            sendTradeRequest(user)
        elseif curTradeStatus == "ReceivingRequest" then
            Trade.DeclineRequest:FireServer()
            wait(0.5)
        end
        wait(2)
    end
    log(string.format("发货orderId:%s user:%s item:%s 交易状态：StartTrade", orderId, user, itemId))
    local itemArgs = {
        [1] = itemId,
        [2] = "Weapons"
    }
    Trade.OfferItem:FireServer(unpack(itemArgs))
    log(string.format("发货orderId:%s user:%s item:%s OfferItem", orderId, user, itemId))
    wait(7)
    local acceptArgs = {
        [1] = game_id
    }
    Trade.AcceptTrade:FireServer(unpack(acceptArgs))
    log(string.format("发货orderId:%s user:%s item:%s 自己 AcceptTrade", orderId, user, itemId))
    while true do
        local curTradeStatus, tradeData = getCurTradeStatus()
        if curTradeStatus == "None" then
            log(string.format("发货orderId:%s user:%s item:%s 交易成功", orderId, user, itemId))
            break
        end
        wait(1)
    end
end

local function run()
    while true do
        -- 收货
        local ReceivingData = getReceivingOrder()
        if ReceivingData["order_id"] then
            runReceiving(ReceivingData)
        else
            wait(120)
        end
        --wait(2)
        -- 发货
        --local DeliveryData = getDeliveryOrder()
        --if DeliveryData["order_id"] then
        --    runDelivery(DeliveryData)
        --end
    end
end

task.spawn(run)